import { AppDataSource } from '../config/database';
import { BranchAccount } from '../entity/BranchAccount';
import { getStrategy } from '../brand/strategyFactory';

/**
 * 刷新所有数据库中token
 */
export async function refreshAllTokens() {
  const repo = AppDataSource.getRepository(BranchAccount);
  const records = await repo.find();

  for (const record of records) {
    const { userId, brand, token } = record;

    try {
      const strategy = getStrategy(brand);
      if (!strategy.refreshToken) {
        console.log(`[REFRESH] ${brand} 不支持 refreshToken`);
        continue;
      }

      const { access_token, expires_in } = await strategy.refreshToken(userId, token);
      const expiresAt = new Date(Date.now() + expires_in * 1000 * 3600);

      record.token = access_token;
      record.expiresInHour = expires_in;
      record.expiresAt = expiresAt;
      await repo.save(record);

      console.log(`[REFRESH] ${userId}@${brand} token refresh successfully`);
    } catch (err: any) {
      console.error(`[REFRESH] ${userId}@${brand} refresh failed: ${err.message}`);
    }
  }
}
